import {
  userCollection,
  log,
  getConfig
} from '../share/index'
import uniToken from './uni-token'
import {
  verifyCode
} from './verify'
import loginCheck from '../common/login-check'
import encryptPwd from './encrypt-pwd'
import registerExec from '../common/register-exec'

async function loginBySms ({
  mobile,
  code,
  password,
  inviteCode,
  myInviteCode,
  type
}) {
  const config = getConfig()
  if (config.forceInviteCode && !type) {
    // 此类给开发者看的错误应直接抛出
    throw new Error('[loginBySms]强制使用邀请码注册时，需指明type为register还是login')
  }
  const verifyRes = await verifyCode({
    mobile,
    code,
    type: type || 'login'
  })
  if (verifyRes.code !== 0) {
    return verifyRes // 验证失败
  }
  const query = {
    mobile,
    mobile_confirmed: 1
  }
  const userInDB = await userCollection.where(query).get()

  log('userInDB:', userInDB)

  if (userInDB && userInDB.data && userInDB.data.length > 0) {
    if (type === 'register') {
      return {
        code: 10201,
        msg: '此手机号已注册'
      }
    }
    const userMatched = userInDB.data[0]
    try {
      const loginCheckRes = await loginCheck(userMatched)
      if (loginCheckRes.code !== 0) {
        return loginCheckRes
      }
      const tokenList = loginCheckRes.user.token

      log('开始修改最后登录时间')

      const {
        token,
        tokenExpired
      } = uniToken.createToken(userMatched)
      log('token', token)
      tokenList.push(token)
      const upRes = await userCollection.doc(userMatched._id).update({
        last_login_date: new Date().getTime(),
        last_login_ip: __ctx__.CLIENTIP,
        token: tokenList
      })

      log('upRes', upRes)

      return {
        code: 0,
        token: token,
        uid: userMatched._id,
        username: userMatched.username,
        mobile,
        userInfo: userMatched,
        type: 'login',
        msg: '登录成功',
        tokenExpired: tokenExpired
      }
    } catch (e) {
      log('写入异常：', e)
      return {
        code: 90001,
        msg: '数据库写入异常'
      }
    }
  } else {
    // 注册用户
    const now = Date.now()
    if (type === 'login') {
      return {
        code: 10203,
        msg: '此手机号尚未注册'
      }
    }
    const user = {
      mobile: mobile,
      mobile_confirmed: 1,
      register_ip: __ctx__.CLIENTIP,
      register_date: now
    }
    if (type === 'register') {
      if (password) {
        user.password = encryptPwd(password)
      }
      if (inviteCode) {
        const inviter = await userCollection.where({
          my_invite_code: inviteCode
        }).get()
        if (inviter.data.length !== 1) {
          return {
            code: 10202,
            msg: '邀请码无效'
          }
        }
        // 倒序排列全部邀请人
        user.inviter_uid = ([inviter.data[0]._id]).concat(inviter.data[0].inviter_uid || [])
        user.invite_time = now
      } else if (config.forceInviteCode) {
        return {
          code: 10202,
          msg: '邀请码无效'
        }
      }
      if (myInviteCode) {
        user.my_invite_code = myInviteCode
      }
    }
    const registerResult = await registerExec(user)
    if (registerResult.code > 0) {
      return registerResult
    }
    const addRes = registerResult.result
    log('addRes', addRes)
    const uid = addRes.id

    if (addRes.id) {
      const {
        token,
        tokenExpired
      } = uniToken.createToken({
        _id: uid
      })
      await userCollection.doc(uid).update({
        token: [token]
      })
      return {
        code: 0,
        uid,
        mobile,
        type: 'register',
        msg: '登录成功',
        token,
        tokenExpired
      }
    }
    return {
      code: 90001,
      msg: '数据库写入失败'
    }
  }
}

export default loginBySms
